package com.qf.fmall.shopcart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall.product.entity.Product;
import com.qf.fmall.product.entity.ProductImg;
import com.qf.fmall.product.entity.ProductSku;
import com.qf.fmall.product.mapper.ProductImgMapper;
import com.qf.fmall.product.mapper.ProductMapper;
import com.qf.fmall.product.mapper.ProductSkuMapper;
import com.qf.fmall.shopcart.entity.ShoppingCart;
import com.qf.fmall.shopcart.mapper.ShoppingCartMapper;
import com.qf.fmall.shopcart.service.IShoppingCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wbw
 * @since 2023-11-30
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements IShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductImgMapper productImgMapper;
    @Autowired
    private ProductSkuMapper productSkuMapper;
    @Override
    public List<ShoppingCart> cartList(Integer userId) {//Integer userId
        //1.根据userid查询购物车表
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<ShoppingCart> carts = shoppingCartMapper.selectList(wrapper);
        addCarts(carts);
        return carts;
    }

    @Override
    public List<ShoppingCart> listbycids(List<Integer> cids) {
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectBatchIds(cids);
        addCarts(shoppingCarts);
        return shoppingCarts;
    }

    private void addCarts(List<ShoppingCart> carts) {
        for (ShoppingCart cart : carts) {
            Integer productId = cart.getProductId();
            Product product = productMapper.selectById(productId);
            cart.setProductName(product.getProductName());

            ProductImg productImg = productImgMapper.selectOne(new QueryWrapper<ProductImg>().eq("product_id", productId).eq("is_main", 1));
            cart.setProductImg(productImg.getUrl());

            String skuId = cart.getSkuId();

            ProductSku productSku = productSkuMapper.selectById(skuId);

            cart.setSkuName(productSku.getSkuName());

            cart.setOriginalPrice(productSku.getOriginalPrice());

            cart.setSellPrice(productSku.getSellPrice());

            cart.setStock(productSku.getStock());

        }
    }
}
